import { Component } from 'react'
import ReactDOM from 'react-dom'
import './style/base.css'
import './style/index.css'
import TodoHeader from './TodoHeader.js'
import TodoMain from './todoMain.js'
import TodoFooter from './TodoFooter.js'
class App extends Component {
  state = {
    /*
    [
      { id: 1, name: '吃饭', done: false },
      { id: 2, name: '抽烟', done: true },
      { id: 3, name: '烫头', done: false },
    ]
    */
    list: [],
    type: 'all'
  }
  render() {
    const { list, type } = this.state
    return <div>
      <section className="todoapp">
        <TodoHeader addTodo={this.addTodo}></TodoHeader>
        <TodoMain
          list={list}
          type={type}
          checkAll={this.checkAll}
          editTodo={this.editTodo}
          updateDone={this.updateDone}
          delTodoById={this.delTodoById}></TodoMain>
        <TodoFooter
          handleClick={this.handleClick}
          clearTodo={this.clearTodo}
          list={list}
          type={type}></TodoFooter>
      </section>
    </div>
  }
  delTodoById = (id) => {
    this.setState({
      list: this.state.list.filter(v => v.id !== id)
    })
  }
  updateDone = (id) => {
    // const todo = this.state.list.find(v => v.id === id)
    this.setState({
      list: this.state.list.map(v => {
        if (v.id === id) {
          return {
            ...v,
            done: !v.done
          }
        } else {
          return v
        }
      })
    })
  }
  addTodo = (name) => {
    this.setState({
      list: [
        {
          id: Date.now(),
          name,
          done: false,
        },
        ...this.state.list,
      ]
    })
  }
  editTodo = (id, name) => {
    this.setState({
      list: this.state.list.map(v => {
        if (v.id === id) {
          return {
            ...v,
            name: name
          }
        } else {
          return v
        }
      })
    })
  }
  clearTodo = () => {
    this.setState({
      list: this.state.list.filter(v => !v.done)
    })
  }
  handleClick = (type) => {
    this.setState({
      type: type
    })
  }
  checkAll = (check) => {
    this.setState({
      list: this.state.list.map(v => {
        return {
          ...v,
          done: check
        }
      })
    })
  }
  componentDidMount() {
    this.setState({
      list: JSON.parse(localStorage.getItem('todos'))
    })
  }
  componentDidUpdate() {
    localStorage.setItem('todos', JSON.stringify(this.state.list))
  }
}

ReactDOM.render(<App></App>, document.getElementById('root'))